package com.lemote.action.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lemote.action.BaseAction;
import com.lemote.core.Page;
import com.lemote.core.PropertyFilter;
import com.lemote.entity.CircuitBoard;
import com.lemote.entity.Flow;
import com.lemote.entity.FlowTask;
import com.lemote.entity.OrderEntity;
import com.lemote.entity.PackageBox;
import com.lemote.entity.ShowEntity;
import com.lemote.entity.User;
import com.lemote.exception.AppException;
import com.lemote.service.order.CircuitBoardService;
import com.lemote.service.order.FlowService;
import com.lemote.service.order.FlowTaskService;
import com.lemote.service.order.OrderService;
import com.lemote.service.order.PackAgeBoxService;
import com.lemote.service.order.ShowEntityService;
import com.lemote.utils.CheckUtils;
import com.lemote.utils.Constant;
import com.lemote.utils.StringUtils;

/**
 * 
 * @author slaton
 * @time 2011-7-16 上午10:47:04
 * @Version:0.0.1
 * @since smt
 */
@Component("orderAction")
public class OrderAction extends BaseAction<OrderEntity, OrderService> {

	private OrderEntity orderEntity;

	private FlowService flowService;

	private FlowTaskService flowTaskService;

	private CircuitBoardService circuitBoardService;
	
	private ShowEntityService showEntityService;
	

	/**
	 * 开始订单提示
	 */
	private String msg;

	@Override
	public String delete() throws AppException {
		if (ids != null && ids.length() > 0) {
			for (Long oid : CheckUtils.stringParse(ids)) {
				entityService.delete(oid);
			}
			
		}
		return SUCCESS;
	}

	@Override
	public String input() throws AppException {

		prepareModel();
		if (orderEntity.getId() == null || "0".equals(orderEntity.getStatus())) {
			return SUCCESS;
		}
		return ERROR;
	}
	
	public String order() {
		prepareModel();
		return SUCCESS;
	}

	@Override
	public String list() throws AppException {

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		page = entityService.search(page, filters);
		return SUCCESS;
	}

	public String start() {
		String id = request.getParameter("order");
		FlowTask startTask = flowTaskService.getTaskByTaskName("order_start");
		if (id != null
				&& !"".equals(org.apache.commons.lang.StringUtils.trim(id))) {
			Long oid = Long.parseLong(id);
			OrderEntity order = entityService.get(oid);
			order.setStatus("1");
			order.setStartDate(new Date());
			order.setBadNum(0);
			order.setCompleteNum(0);
			order.setRepairNum(0);
			FlowTask flowTask = flowTaskService.getTaskByTaskName("bot_aoi_test");
			List<CircuitBoard> boards = order.getBoards();
			for (CircuitBoard c : boards) {
				c.setFlowTask(flowTask);
				c.setPreTask(startTask);
			}
			entityService.update(order);
		}
		this.msg = "Y";
		return SUCCESS;
	}

	@Override
	public void prepareModel() {
		if (id != null) {
			orderEntity = entityService.get(id);
		} else {
			orderEntity = new OrderEntity();
		}
	}

	@Override
	public String save() throws AppException {
		setBackUrl("order/list.htm");
		if (orderEntity != null) {
			if (orderEntity.getId() == null) {
				Flow flow = flowService.get(1L);
				orderEntity.setFlow(flow);
				entityService.add(saveOrder(orderEntity));
				ShowEntity show = addShow();
				showEntityService.add(show);
			} else {
				entityService.update(saveOrder(orderEntity));
				ShowEntity show = addShow();
				showEntityService.update(show);
			}
			return GLOBALSUCCESS;
		}
		return ERROR;
	}

	private ShowEntity addShow() {
		ShowEntity show = showEntityService.get("orderNo", orderEntity.getOrderNo());
		if (show==null) {
			show = new ShowEntity();
		}
		show.setDipCompleteNum(0);
		show.setDipRepairNum(0);
		show.setDipYield(0);
		show.setSmtCompleteNum(0);
		show.setSmtRepairNum(0);
		show.setSmtYield(0);
		show.setFtCompleteNum(0);
		show.setFtRepairNum(0);
		show.setFtYield(0);
		show.setOrderNo(orderEntity.getOrderNo());
		show.setProductName(orderEntity.getProductName());
		show.setTotal(orderEntity.getNum());
		show.setSeNo(orderEntity.getIcStartNo()+"-"+orderEntity.getIcEndNo());
		return show;
	}

	private OrderEntity saveOrder(OrderEntity orderEntity) {
		User user = (User) request.getSession().getAttribute(
				Constant.SESSION_USER);
		orderEntity.setStatus("0");
		orderEntity.setCreateDate(new Date());
		List<CircuitBoard> boards = createCircuitBoard(orderEntity);
		int total = boards.size();
		orderEntity.setNum(total);
		int num = total / orderEntity.getPacksize();
		if (total % orderEntity.getPacksize() > 0) {
			orderEntity.setPackNum(num + 1);
		} else {
			orderEntity.setPackNum(num);
		}
		orderEntity.setOrderUser(user);
		orderEntity.setBoards(boards);
		orderEntity.setThrough(boards.size());
		return orderEntity;
	}

	private List<CircuitBoard> createCircuitBoard(OrderEntity orderEntity) {
		List<CircuitBoard> boards = new ArrayList<CircuitBoard>();
		List<Long> ids = new ArrayList<Long>();
		if (orderEntity!=null&&orderEntity.getBoards()!=null) {
			List<CircuitBoard> bds = orderEntity.getBoards();
			if (bds!=null) {
				for (CircuitBoard circuitBoard : bds) {
					ids.add(circuitBoard.getId());
				}
			}
		}
		if (ids.size()>0) {
			circuitBoardService.delete(ids);
		}
		Flow flow = orderEntity.getFlow();
		FlowTask flowTask = null;
		List<FlowTask> fts = flow.getTasks();
		if (fts != null) {
			for (FlowTask ft : fts) {
				if ("order_start".equals(ft.getTaskEname())) {
					flowTask = ft;
				}
			}
		}
		String endNo = orderEntity.getIcEndNo();
		String startNo = orderEntity.getIcStartNo();
		String sameStr = StringUtils.getSameString(startNo, endNo);
		String endStr = endNo.substring(sameStr.length(), endNo.length());
		String startStr = startNo.substring(sameStr.length(), startNo.length());
		if (endStr == null || startStr == null) {
			return null;
		}
		Integer eno = Integer.parseInt(endStr);
		Integer sno = Integer.parseInt(startStr);
		while (eno >= sno) {
			StringBuffer sb = new StringBuffer(sameStr);
			CircuitBoard board = new CircuitBoard();
			board.setFlowTask(flowTask);
			if (String.valueOf(eno).length()==String.valueOf(sno).length()) {
				board.setIcNo(sb.append(sno).toString());
			}else{
				for (int i=0; i<String.valueOf(eno).length()-String.valueOf(sno).length();i++) {
					sb.append(0);
				}
				board.setIcNo(sb.append(sno).toString());
			}
			board.setOrderEntity(orderEntity);
			board.setStatus("0");
			board.setRtimes(0);
			board.setAnalyzes(0);
			board.setOrderNo(orderEntity.getOrderNo());
			board.setSystemName(orderEntity.getSystemName());
			board.setSystemVersion(orderEntity.getSystemVersion());
			board.setPmonVersion(orderEntity.getPmonVersion());
			board.setProgramVersion(orderEntity.getProgramVersion());
			boards.add(board);
			sno++;
		}
		return boards;
	}

	public String packList() {

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		PropertyFilter filter = new PropertyFilter("EQB_pack", "1");
		filters.add(filter);
		page = entityService.search(page, filters);
		return SUCCESS;
	}
	
	/**
	 * 大屏幕实时显示
	 * @return
	 */
	public String show(){
		String ono = request.getParameter("order");
		if (ono==null) {
			return ERROR;
		}
		orderEntity = entityService.getOrderByNo(ono);
		return SUCCESS;
	}
	
	/**
	 * 结单
	 * @return
	 */
	public String endOrder(){
		if (id!=null) {
			orderEntity = entityService.get(id);
			boolean flag = true;
			List<CircuitBoard> cbs = orderEntity.getBoards();
			if (cbs!=null) {
				for (CircuitBoard cb : cbs) {
					if (cb.getBox()==null&&!"2".equals(cb.getStatus())) {
						flag = false;
						break;
					}
				}
			}
			if (flag) {
				orderEntity.setStatus("2");
				entityService.update(orderEntity);
				this.msg = "Y";
			}else {
				this.msg = "N";
			}
		}
		return SUCCESS;
	}
	

	@Autowired
	@Override
	public void setEntityService(OrderService orderService) {

		this.entityService = orderService;
	}

	@Override
	@JSON(serialize=false,deserialize=false)
	public OrderEntity getModel() {

		return orderEntity;
	}

	@JSON(serialize=false,deserialize=false)
	public OrderEntity getOrderEntity() {
		return orderEntity;
	}

	public void setOrderEntity(OrderEntity orderEntity) {
		this.orderEntity = orderEntity;
	}

	@Autowired
	public void setFlowService(FlowService flowService) {
		this.flowService = flowService;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Autowired
	public void setCircuitBoardService(CircuitBoardService circuitBoardService) {
		this.circuitBoardService = circuitBoardService;
	}

	@Autowired
	public void setFlowTaskService(FlowTaskService flowTaskService) {
		this.flowTaskService = flowTaskService;
	}
	
	
	
	@Autowired
	public void setShowEntityService(ShowEntityService showEntityService) {
		this.showEntityService = showEntityService;
	}
}
